<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
<#include "head.ftl" />
<style>
.param {
	width: 710px;
	margin: 0 0 0 15px;
	padding: 20px 0 20px 0;
	border:0;
	border-top: 1px solid #aaa;
	border-bottom: 1px solid #aaa;
}

.button {
	line-height:0; margin:0; width:16px; height:16px; display: inline-block; *vertical-align:middle;
	border:0 none; cursor: pointer;outline:none;
	background-color:transparent; background-repeat:no-repeat; background-attachment: scroll;
	background-image:url("${st.resDomain}/common/js/ztree/css/img/zTreeStandard.png"); *background-image:url("${st.resDomain}/common/js/ztree/css/img/zTreeStandard.gif")
}
 
.remove {
	margin-left:5px; background-position:-110px -64px; *vertical-align:middle; *vertical-align:middle 
} 

.selectPic {
	vertical-align:middle; 
}

.img {
	height: auto;
	width: 50px
}

</style>
</head>
<body>
<div class="body-box">
	<div class="rhead">
		<div class="rpos">当前位置: 地区 - 列表</div>
		<div class="clear"></div>
		
	</div>
	<div style="margin-top:20px;">
		<div style="clear:both;margin-left:50px;width:250px;float:left;">
			<div id="regionList" class="ztree"></div>
	    </div>
	    <div id="editDiv" style="float:left;margin-left:50px;border:1px solid #bbe1f1;background:#eefaff;">
	     
		</div>
	</div>
</div>
<div id="paramTmp" style="display:none;">
 <div class="param">
  <span style="font-weight:700;font-size:20px;">-{name}-</span>&nbsp;(-{spell}-)
  <div style="margin-left:5px;">
   <p>经纬度：<span>-{lnglat}-</span></p>
  </div>
 </div>
 <div class="param">
  <div>
   <div style="float:left;font-weight:700;font-size:12px;">广告</div>
   <div style="float:right;margin-right:5px;"><input id="addAdBt" type="button" value="新增广告"/></div>
  </div>
  <table id="adTable" width="100%" class="pn-ftable" cellpadding="2" cellspacing="1" border="0" style="margin-top:40px;">

  </table>
  <div style="margin-left:5px;margin-top:5px;"><label>覆盖子地区<input type="checkbox" name="aCoverType"/></label></div>
  <div style="height:30px;"><input id="submit_ad_bt" type="button" value="保存" style="float:right;margin-right:5px;"/></div>
 </div>
 <div class="param">
  <div>
   <div style="float:left;font-weight:700;font-size:12px;">热词</div>
   <div style="float:right;margin-right:5px;"><input id="addWordBt" type="button" value="新增热词"/></div>
  </div>
  <table id="wordTable" width="100%" class="pn-ftable" cellpadding="2" cellspacing="1" border="0" style="margin-top:40px;">
  </table>
  <div style="margin-left:5px;margin-top:5px;"><label>覆盖子地区<input type="checkbox" name="wCoverType"/></label></div>
  <div style="height:30px;"><input id="submit_word_bt" type="button" value="保存" style="float:right;margin-right:5px;"/></div>
 </div>
</div>
</body>
<script>
	//加载地区列表请求地址
	var listRegionPath = g_domain + "/region/listByParentId/json";
	//新增地区请求地址
	var addRegionPath = g_domain + "/region/addDo/json";
	//编辑地区请求地址
	var editRegionPath = g_domain + "/region/editDo/json";
	//删除地区请求地址
	var delRegionPath = g_domain + "/region/delDo/json";
	// 节点选中的地区
	var region = null;
	
	var setting = {
		view : {
			addHoverDom : addHoverDom,
			removeHoverDom : removeHoverDom,
			selectedMulti : false
		},
		async : {
			enable : true,
			autoParam : ["regionId=parentId"],
			dataFilter : dataFilter,
			url : "listByParentId/json"
		},
		edit : {
			enable : true,
			renameTitle : "编辑",
			removeTitle : "删除",
			editNameSelectAll : true
		},
		data : {
			keep : {
				leaf : false,
				parent : true
			},
			key : {
				name : "name"
			},
			simpleData : {
				enable : true,
				idKey : "regionId",
				pIdKey : "parentId",
				rootPId : null
			}
		},
		callback : {
			beforeRename : beforeRename,
			beforeRemove : beforeRemove,
			onClick : treeNodeOnClick
		}

	};
	
	var zTree = null;
	$(document).ready(function() {
		initZTree(null, function(){
			zTree = $.fn.zTree.getZTreeObj("regionList");
			var nodes = zTree.transformToArray(zTree.getNodes());
			for (var i = 0; i < nodes.length; i++) {
				var n = nodes[i].level;
				if (n == 0) {
					zTree.expandNode(nodes[i], true, false, false);
				}
			}
		});
	});
	
	function initZTree(parentNode, callback) {
		var parentId = 0;
		if(parentNode){
			parentId = parentNode.regionId;
		}
		$.getJSON(listRegionPath, {parentId:parentId}, function(data) {
			var list = data.result;
			var nodes = [];
			for (var i = 0; i < list.length; i++) {
				var node = list[i];
				node.isParent = true;
				nodes.push(node);
			}
			$.fn.zTree.init($("#regionList"), setting, nodes);
			if(callback){
				callback();
			}  
		});
	}
	
	function dataFilter(treeId, parentNode, responseData) {
		if (!responseData) return null;
		var list = responseData.result;
		var childNodes = [];
		if(!list){
			return;
		}
		for (var i = 0; i < list.length; i++) {
			var node = list[i];
			node.isParent = true;
			node.open = true;
			childNodes.push(node);
		}
		return childNodes;
	} 
	
	//显示“新增”按钮，并绑定操作事件
	function addHoverDom(treeId, treeNode) {
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增'  onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_" + treeNode.tId);
		if (btn) {
			btn.bind("click", function () {
				$.ajax({
					url : addRegionPath,
					type : "post",
					dataType : "json",
					data : {"parentId" : treeNode.regionId , "type" : treeNode.type},
					success : function (data) {
						if(data.status !== 0){
							alert(data.message);
							return;
						}
						var node = data.result;
						node.isParent = true;
						zTree = $.fn.zTree.getZTreeObj("regionList");
						if (treeNode.zAsync) {
							zTree.addNodes(treeNode, node);
						} else {
							zTree.reAsyncChildNodes(treeNode, "refresh");
						}
						
					}
				});
			});
		}
	}
	
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_" + treeNode.tId).unbind().remove();
	}
	
	//编辑地区名称提交前回调函数，把更新内容提交至服务器
	function beforeRename(treeId, treeNode, newName){
		if(newName == treeNode.name) {
			return true;
		}
		//根据ajax请求结果， 确定回调函数的返回值
		var eFlag = false;
		$.ajax({
			url : editRegionPath,
			async : false,
			type : "post",
			dataType : "json",
			data : {"regionId" : treeNode.regionId , "name" : newName},
			success : function (data) {
				if(data.status === 0){
					eFlag = true;
				}
			}
		});
		if (!eFlag) {
			alert("更新失败,请重试或者联系管理员!");
		}
		return eFlag;
	}
	
	//删除地区节点回调函数
	function beforeRemove(treeId, treeNode) {
		zTree = $.fn.zTree.getZTreeObj("regionList");
		zTree.selectNode(treeNode);
		var delFlag = window.confirm("确定要删除" + treeNode.name + "及其所有子地区？");
		if (!delFlag) {
			return false;
		}
		//根据ajax请求结果， 确定回调函数的返回值
		var dFlag = false;
		$.ajax({
			url : delRegionPath,
			async : false,
			type : "post",
			dataType : "json",
			data : {"regionId" : treeNode.regionId},
			success : function (data) {
				if(data.status === 0){
					dFlag = true;
				}
			}
		});
		if (!dFlag) {
			alert("删除失败,请重试或者联系管理员!");
		}
		return dFlag;
	}
	
	// 单击节点回调函数
	function treeNodeOnClick(event, treeId, treeNode) {
		$("#editDiv").empty();
		var ads = $.parseJSON(treeNode.ads).mob;
		var words = $.parseJSON(treeNode.words).mob;
		var adsHtml = "";
		var wordsHtml = "";
		for (var i = 0; i < ads.length; i++) {
			var ad = ads[i];
			adsHtml += '<tr>' + 
				'<td width="5%" class="pn-flabel pn-flabel-h"><span class="pn-frequired">*</span>广告:</td>' + 
				'<td colspan="1" width="25%" class="pn-fcontent"><input type="text" name="imgSrc" value="' + ad.img + '" class="required"' +
				 'style="width:250px;" /><br> <br> <img id="add_imgPrev"' +
				 'src="' + g_attaDomain + ad.img + '" class="atta thumbImage"> <input type="button"' +
				 'class="selectPic" value="选择图片"></td>' + 
				'<td colspan="1" width="25%" class="pn-fcontent"><p><span ' +
				 'class="pn-frequired">*</span>链接:<input type="text" name="adUrl" value="' + ad.url + '" style="width:250px;"/></p></td>' + 
				'<td width="5%" class="pn-flabel pn-flabel-h" style="text-align: center;"><span class="button remove" title="删除"></span></td>'
		  		'</tr>';
		}
		for (var i = 0; i < words.length; i++) {
			var word = words[i];
			wordsHtml += '<tr>' + 
				'<td width="5%" class="pn-flabel pn-flabel-h"><span class="pn-frequired">*</span>热词:</td>' + 
				'<td colspan="1" width="25%" class="pn-fcontent"><input type="text" name="word" value="' + word.word + '" class="required"' +
				 'style="width:250px;" /></td>' + 
				'<td colspan="1" width="25%" class="pn-fcontent"><p><span ' +
				 'class="pn-frequired">*</span>链接:<input type="text" name="wUrl" value="' + word.url + '" style="width:250px;"/></p></td>' + 
				'<td width="5%" class="pn-flabel pn-flabel-h" style="text-align: center;"><span class="button remove" title="删除"></span></td>'
				'</tr>';
		}
		$("#paramTmp").find("#adTable").empty();
		$("#paramTmp").find("#wordTable").empty();
		$("#paramTmp").find("#adTable").append(adsHtml);
		$("#paramTmp").find("#wordTable").append(wordsHtml); 
		var tmp = $("#paramTmp").html();
		tmp = tmp
			.replace(/\-\{name\}\-/g, treeNode.name)
			.replace(/\-\{lnglat\}\-/g, treeNode.lnglat)
			.replace(/\-\{spell\}\-/g, treeNode.spell);
		$("#editDiv").append(tmp);
		region = treeNode;
	}
	
	// 事件： 新增广告
	$(document).on("click", "#addAdBt", function() {
		var addAdHtml = '<tr>' + 
			'<td width="5%" class="pn-flabel pn-flabel-h"><span class="pn-frequired">*</span>广告:</td>' + 
			'<td colspan="1" width="25%" class="pn-fcontent"><input type="text" name="imgSrc" value="" class="required"' +
			 'style="width:250px;" /><br> <br> <img id="add_imgPrev"' +
			 'src="" class="atta thumbImage"> <input type="button"' +
			 'class="selectPic" value="选择图片"></td>' + 
			'<td colspan="1" width="25%" class="pn-fcontent"><p><span ' +
			 'class="pn-frequired">*</span>链接:<input type="text" name="wUrl" value="" style="width:250px;"/></p></td>' + 
			'<td width="5%" class="pn-flabel pn-flabel-h" style="text-align: center;"><span class="button remove" title="删除"></span></td>'
	  		'</tr>';
		$("#adTable").append(addAdHtml);
	});
	
	// 事件：点击广告/热词删除按钮
	$(document).on("click", ".button.remove", function() {
		$(this).closest("tr").remove();
	});
	
	// 事件：新增热词
	$(document).on("click", "#addWordBt", function() {
		var addWordHtml = '<tr>' + 
			'<td width="5%" class="pn-flabel pn-flabel-h"><span class="pn-frequired">*</span>热词:</td>' + 
			'<td colspan="1" width="25%" class="pn-fcontent"><input type="text" name="word" value="" class="required"' +
			 'style="width:250px;" /></td>' + 
			'<td colspan="1" width="25%" class="pn-fcontent"><p><span ' +
		 	 'class="pn-frequired">*</span>链接:<input type="text" name="wUrl" value="" style="width:250px;"/></p></td>' + 
			'<td width="5%" class="pn-flabel pn-flabel-h" style="text-align: center;"><span class="button remove" title="删除"></span></td>'
	  		'</tr>';
		$("#wordTable").append(addWordHtml);
	});
	
	var $picEl = null; // 选择广告图片按钮的点击事件
	
	var finderForAd = new CKFinder();
	finderForAd.resourceType = 'Images';
	finderForAd.selectActionData = "container";
	finderForAd.selectActionFunction = function(fileUrl, data) {
		$picEl.prevAll("[name='imgSrc']").val(fileUrl);
		$picEl.prevAll("img").attr("src",g_attaDomain + fileUrl);
	};
	
	$(document).on("click", ".selectPic", function() {
		finderForAd.popup();
		$picEl = $(this);
	});
	
	// 事件：保存广告
	$(document).on("click", "#submit_ad_bt", function() {
		var ads = "";
		var regionId = region.regionId;
		$("#adTable").find("tr").each(function() {
			var imgSrc = $(this).find("[name='imgSrc']").val();
			var adUrl = $(this).find("[name='adUrl']").val();
			ads += '{"img":"' + imgSrc + '","url":"' + adUrl + '"},';
		});
		ads = ads.substring(0, ads.length-1);
		var mobileAds = '{"mob":[' + ads + ']}';
		// 是否覆盖 *不覆盖值为0，覆盖值为1
		var coverType = region.coverType;
		if ($("[name='aCoverType']").is(":checked")) {
			coverType = coverType | (1 << 0);   // 广告枚举下标为0
		} else {
			coverType = coverType & ~(1 << 0);
		}
		var param = {
			regionId: regionId,
			ads: mobileAds,
			coverType: coverType
		};
		$.post(editRegionPath, param, function(data) {
			var msg = "";
			if (data.status !== 0) {
				msg = "保存失败，请联系管理员"
			} else {
				msg = "保存成功";
			}
			alert(msg);
		});
	});
	
	// 事件：保存热词
	$(document).on("click", "#submit_word_bt", function() {
		var words = "";
	//	var regionId = $("[name='regionId']").val();
		var regionId = region.regionId;
		$("#wordTable").find("tr").each(function() {
			var word = $(this).find("[name='word']").val();
			var wUrl = $(this).find("[name='wUrl']").val();
			words += '{"word":"' + word + '","url":"' + wUrl + '"},';
		});
		words = words.substring(0, words.length-1);
		var mobileWords = '{"mob":[' + words + ']}';
		// 是否覆盖 *不覆盖值为0，覆盖值为1
		var coverType = region.coverType;
		if ($("[name='wCoverType']").is(":checked")) {
			coverType = coverType | (1 << 1);   // 热词枚举下标为1
		} else {
			coverType = coverType & ~(1 << 1);
		}
		var param = {
			regionId: regionId,
			words: mobileWords,
			coverType: coverType
		};
		$.post(editRegionPath, param, function(data) {
			var msg = "";
			if (data.status !== 0) {
				msg = "保存失败，请联系管理员"
			} else {
				msg = "保存成功";
			}
			alert(msg);
		});
	});
	
</script>
</html>